<template>
  <s-layout
    title="社群"
    color="#333"
    navbar="custom1"
    :onShareAppMessage="state.shareData"
  >
    <view v-if="isAuditMode==true">开发中敬请期待！！！</view>
    
		<!-- 顶部简介 -->
	<view v-if="isAuditMode==false">
		<view class="top-bg">
			<assNavbar
			  title="商学院"
			  :color="state.top_show?'':'#fff'"
			  :background="{ BGcolor: state.top_show?'#fff':'transparent', img: 'none' }"
			></assNavbar>
			<view class="top-info ss-flex align-start ss-m-t-50">
				<image
				  :src="sheep.$url.cdn(state.talkData.image)"
				  mode="aspectFill"
				/>
				<view class="ss-m-l-40 font-w">
					<view class="font-2 ss-m-b-12 ss-line-1">{{ state.talkData.title }}</view>
					<view class="font-1 ss-line-2">{{ state.talkData.sub_title }}</view>
				</view>
			</view>
		</view>
		
		<!-- 发布内容 -->
		<view class="ss-r-20 bg-white ss-p-y-20 ss-p-x-30">
			<view class="ss-flex justify-between">
				<view class="font-w font-1 gray">发布内容</view>
				<button
				class="btn-box-style ss-reset-button"
				@click="downRefCilck"
				v-if="state.talkData?.files?.length>0"
				>
				<image
				  class="icon-style"
				  src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250516/c5820e3e58433cfad5f9d010b974aab5.png"
				  mode="scaleToFill"
				/>
				下载附件
				</button >
			</view>
			<view class="line ss-m-y-20"></view>
			<!-- style="background-color:#C8C8C8;overflow: hidden;" -->
				<!-- <su-swiper
				  imageMode="aspectFill"
				  :isPreview="true"
				  :list="state.swiperList"
				></su-swiper> -->
					<mp-html :content="state.talkData?.content"
					></mp-html>
				
				<!-- <view
				  class="article-content"
				  v-html="state.talkData?.content"
				> </view> -->
				
				
			<!-- 内容标签   暂无  隐藏-->
			<template v-if="state.talkData.tags?.length">
				<view class="font-w font-1 gray ss-m-y-20">内容标签</view>
				<view class="line ss-m-t-14 ss-m-b-10"></view>
				<view class="tag-box">
					<view class="tag-item" v-for="(item,index) in state.talkData.tags" :key="index">{{item}}</view>
				</view>
			</template>
			
		</view>
     
	 
	 <!-- 推荐内容  接口暂无  隐藏 -->
	<view class="article ss-r-20 bg-white ss-m-t-10 ss-p-y-20 ss-p-x-30">
		<view class="font-1 font-w ">推荐内容</view>
		<view class="line ss-m-y-20"></view>
		<template v-for="(item,index) in state.talkData.recommend" :key="index">
			<view v-if="index<4" @tap="sheep.$router.go('/association/pages/talkDetail',{id:item.id})" class="list-item ss-flex">
				<image
				  :src="sheep.$url.cdn(item.image)"
				  mode="aspectFill"
				/>
				<view class="right">
					<view class="font-2 font-w ss-line-1">{{item.title}}</view>
					<view class="tag-box ss-line-1 ss-m-y-8">
						<view class="tag-item" v-for="(tag,ind) in item.tags" :key="ind">{{tag}}</view>
					</view>
					<view class="font-1 font-w ss-line-1">{{item.text}}</view>
				</view>
			</view>
			<view class="line ss-m-y-20"></view>
		</template>
		
	</view>

	   
      
      <view class="article ss-r-20 bg-white ss-m-t-10 ss-p-y-20 ss-p-x-30">
		<view class="font-1 font-w ">用户评论</view>
		<view class="line ss-m-y-20"></view>
        

        <view class="hotspot ss-flex ss-row-between"> 
          <view class="ss-flex title">{{state.sort == 'likes'?'热度':'最新'}}<view>查看</view>
          </view>
          <view
            class="ss-flex set"
            @click="setComment"
          >
            <view :style="{ backgroundColor: state.sort == 'likes' ? theme.btn_background_color : '' }">热度</view>
            <view class="line"></view>
            <view :style="{
                backgroundColor: state.sort == 'createtime' ? theme.btn_background_color : '',
              }">最新</view>
          </view>
        </view>
		
        <view
          v-if="state.talkData?.comment.length"
          class="article-comment"
        >
          <assComment
            v-for="commentData in state.talkData?.comment"
            :key="commentData.updatatime"
            @del="commentDel"
            @like="commentLike"
            :contnet="commentData"
            @comment="comment(commentData)"
          >
            <!-- <assComment child v-for="childData in commentData.child" :key="childData.updatatime" @del="commentDel"  @like="commentLike"
						:contnet="childData" @comment="comment({...childData,fa_comment_id:commentData.comment_id})"></assComment> -->

            <assComment
              child
              v-for="childData in isFold(commentData.comment_id)
                ? commentData.child
                : commentData.child.slice(0, 1)"
              :key="childData.updatatime"
              @del="commentDel"
              @like="commentLike"
              :contnet="childData"
              @comment="comment({ ...childData, fa_comment_id: commentData.comment_id })"
            ></assComment>
            <view
              v-if="!isFold(commentData.comment_id) && commentData.child.length > 1"
              class="childShow"
              :style="{ color: theme.collapse_color }"
              @click="state.commentFold.push(commentData.comment_id)"
            >
              展开{{ commentData.child.length - 1 }}条回复
            </view>
          </assComment>
        </view>
        <view
          v-else
          style="color: #999"
        >暂无评论</view>
      </view>
	  
	  
      <assReply
        :placeholder="state.placeholder"
        :focus="state.focus"
        @reply="topicComment"
        @cancel="state.focus = false"
      ></assReply>
      <assTalkTabNew
        :articleData="state.talkData"
        @comment="comment"
        @shareFun="shareFun"
      ></assTalkTabNew>
      <!-- 分享列表为空注释 -->
      <popupShare
        v-model:show="state.showShare"
        :findId="state.id"
      ></popupShare>
    </view>
  </s-layout>
</template>

<script setup>
import assNavbar from '@/components/ass-navbar.vue';
import assComment from './components/ass-comment.vue';
import assTalkTabNew from './components/ass-talk-tab-new';
import assReply from './components/ass-reply.vue';
import sheep from '@/sheep';
import API from '../api';
import association from '@/association/store';
import popupShare from "./components/popup-share.vue";
import appApi from '@/sheep/api/app';

import {
  onLoad,
  onShow,
  onPageScroll,
  onPullDownRefresh,
  onShareAppMessage,
  onShareTimeline,
} from '@dcloudio/uni-app';
import { onMounted, nextTick, computed, reactive } from 'vue';

const isAuditMode = computed(() => sheep.$store('app').isAuditMode);

const state = reactive({
  shareData: {
    title: '话题',
    path: '/association/pages/talk',
    image: '',
    desc: '',
  },
  // 评论折叠控制
  commentFold: [],
  // 评论排序
  sort: 'likes',
  focus: false,
  id: '',
  placeholder: '',
  tabsIndex: 0,
  comment_id: 0,
  to_user_id: 0,
  isLike: false,
  talkData: {
    comment: [],
	files:[]
  },
  reply: '',
  swiperList: [],
  showShare: false,
  top_show:false
});

onPageScroll((e) => {
  const {
    scrollTop
  } = e
  if (scrollTop > 40) {
    state.top_show = true
  } else {
    state.top_show = false
  }


})

onShareAppMessage((e) => {
  topicForward();
});
onShareTimeline((e) => {
  topicForward();
  return {
    ...state.shareData,
    imageUrl: state.shareData.image,
  };
});
const isFold = (id) => {
  return state.commentFold.includes(id);
};
const theme = computed(() => association().theme);
const shareFun = () => {
  console.log('点击回调');

  state.showShare = true;
};
const topicForward = async (e) => {
  let res = await API.topicForward({
    topic_id: state.id,
  });
  if (res.code) {
    // uni.showToast({
    // 	icon:'none',
    // 	title:'评论成功',
    // 	duration:1000
    // })
    state.talkData.forward += 1;
  }
};
const comment = (data) => {
  state.focus = false;
  if (data) {
    state.comment_id = data.fa_comment_id != undefined ? data.fa_comment_id : data.comment_id;
    state.to_user_id = data.user_id;
  } else {
    state.comment_id = 0;
    state.to_user_id = 0;
  }
  nextTick(() => {
    state.focus = true;
    state.placeholder = data ? '回复：' + data.nickName : '评论';
  });
};

const topicComment = async (e) => {
  let data = {
    topic_id: state.id,
    content: e.content,
    comment_id: state.comment_id,
    to_user_id: state.to_user_id,
  };
  let res = await API.topicComment(data);
  if (res.code) {
    if (!isFold(state.comment_id)) {
      state.commentFold.push(state.comment_id);
    }
    uni.showToast({
      icon: 'none',
      title: '评论成功',
      duration: 1000,
    });
    getTalkDetails();
  }
};

const setComment = () => {
  state.sort = state.sort == 'likes' ? 'createtime' : 'likes';
  getTalkDetails();
};

const login = async () => {
  let res = await API.login();
};
const downRefCilck = async () => {
   state.talkData?.files.forEach(async item => {
	  await downFilter(item)
  });
}
const downFilter = async (item) => {
  try {
	  console.log('item',item)
    // 1. 显示加载提示
    uni.showLoading({ title: '下载中...' });
    uni.downloadFile({
      url: item,
      success: function (res) {
		  var filePath = res.tempFilePath;
		  // 保存图片到相册
		  if(item.endsWith('png')||item.endsWith('jpg')||item.endsWith('gif')){
			 uni.saveImageToPhotosAlbum({
			   filePath: res.tempFilePath,
			   success: (res) => {
			     sheep.$helper.toast('保存成功');
			   },
			   fail: (err) => {
			     sheep.$helper.toast('保存失败');
			     console.log('图片保存失败:', err);
			   },
			 }); 
		  }else{
			  uni.saveFile({
			    tempFilePath: filePath,
			    success: function ({ savedFilePath }) {
			      if (uni.getSystemInfoSync().platform === 'android') {
			        // 保存
			        uni.saveFileToDisk({
			          filePath: savedFilePath,
			          success: () => {
			            uni.showToast({ title: '已保存到下载目录', icon: 'success' });
			          }
			        });
			      } else {
			        uni.showToast({ title: '文件已保存', icon: 'success' });
			      }
			      uni.openDocument({
			        filePath: savedFilePath,
			        showMenu: true,
			        success: function (resTwo) {
			          // 下载临时路径到本地
			  
			        },
			      });
			    }
			  })
		  }
		  
		  
        
      },
    });
  } catch (err) {
    console.error('下载失败:', err);
    uni.showToast({ title: '下载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
}
onMounted(() => {
  // login()
});
const commentDel = (e) => {
  uni.showModal({
    title: '提示',
    content: '删除后无法恢复',
    success: async (res) => {
      if (res.confirm) {
        let res = await API.topicDelComment({
          comment_id: e.comment_id,
        });
        if (res.code) {
          uni.showToast({
            icon: 'none',
            title: '删除成功',
            duration: 1000,
          });
          getTalkDetails();
        }
      } else if (res.cancel) {
        // uni.showToast({
        // 	icon:'none',
        // 	title:'取消删除',
        // 	duration:1000
        // })
      }
    },
  });
};
const commentLike = async (e) => {
  let res = await API.topicLike({
    comment_id: e.comment_id,
  });
  if (res.code) {
    getTalkDetails();
  }
};
const getTalkDetails = async () => {
  let res = await API.topicDetails({
    topic_id: state.id,
    sort: state.sort,
  });
  state.talkData = res.data;
  state.swiperList = res.data.images.map((src) => {
    let type = src.substring(src.lastIndexOf(".") + 1)
    let imgList = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'svg', 'heif', 'heic', 'psd']
    return {
      url: '',
      type: imgList.indexOf(type) == -1 ? 'video' : 'image',
      src,
    };
  });
  
  if(res.data.tags){
	  state.talkData.tags=res.data.tags.split(',')
  }else{
	  state.talkData.tags=[]
  }
  console.log('state.talkData.tags',state.talkData.tags)
  
  state.talkData.recommend.forEach(item=>{
	  if(item.tags){
		item.tags=item.tags.split(',')  
	  }else{
		  item.tags=[]
	  }
  })
  
  state.shareData = {
    title: state.talkData.title,
    path: `/association/pages/talk?id=${state.id}`,
    image: state.swiperList[0].src,
    desc: state.talkData.sub_title,
  };
};
onLoad(async (e) => {
  state.id = e.id;
  getTalkDetails();
});
</script>

<style>
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
.flex-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.btn-box-style {
  width: 170rpx;
  height: 60rpx;
  border-radius: 20rpx;
  background: #ffffff;
  border: 2rpx solid #d4d4d4;
  font-size: 28rpx;
  color: #797a7c;
  .icon-style {
    width: 30rpx;
    height: 30rpx;
    margin-right: 4rpx;
  }
}
view {
  box-sizing: border-box;
}

.hotspot {
  margin-bottom: 25rpx;

  .title {
    color: #ff6c18;
    font-size: 30rpx;

    & > view {
      font-size: 28rpx;
      color: #3d3d3d;
    }
  }

  .set {
    .line {
      padding: 0px !important;
      width: 3rpx;
      height: 40rpx;
      background-color: #f6f6f6;
    }

    .active {
      background-color: #b5f8ff;
    }

    & > view {
      padding: 10rpx;
      font-size: 24rpx;
      color: #838383;
    }
  }
}

.childShow {
  padding-left: 20rpx;
  font-size: 24rpx;
  margin-bottom: 15rpx;
  color: #1bbdce;
}

.article {
  & > view {
    margin: 20rpx;
  }

  .article-title {
    // margin-top: 40rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
  }

  .article-sub-title {
    color: #555;
    font-size: 28rpx;
  }

  .article-content {
    color: #3d3d3d;
    font-size: 24rpx;
  }

  .article-comment {
    margin-top: 40rpx;
  }
}

.talkList-item {
  margin: 20rpx 20rpx 0;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;

  & > image {
    height: 176rpx;
    width: 176rpx;
    min-width: 176rpx;
    margin-right: 25rpx;
  }

  .talk-info {
    position: relative;
    height: 176rpx;
    max-height: 176rpx;
    color: #3d3d3d;

    .talk-icon {
      position: absolute;
      top: 0;
      right: 0;
    }

    .talk-title {
      font-size: 32rpx;
    }

    .talk-bottom {
      color: #666;
      font-size: 24rpx;

      & > view {
        width: 100rpx;
        height: 40rpx;
        font-size: 20rpx;
        border-radius: 20rpx;
        color: #1bbdce;
        line-height: 40rpx;
        text-align: center;
        background: #b5f8ff;
      }
    }

    .talk-data {
      color: #666;
      font-size: 24rpx;

      & > view {
        width: 33%;

        & > view {
          display: inline-block;
          color: #0ad5ea;
        }
      }
    }
  }
}
.top-bg{
	background: linear-gradient(180deg, #3A332E 0%, #6D655E 100%);
	margin-bottom:-20rpx;
	image{
		width: 120rpx;
		height: 120rpx;
		border-radius: 20rpx;
		flex-shrink: 0;
	}
	.top-info{
		padding:0 40rpx 48rpx 40rpx;
		color:#fff;
	}
}
.gray{
	color:#BABABA
}
.line{
	height:2rpx;
	background-color:#f0f0f0 ;
}
::v-deep.swiper-item{
	border-radius: 20rpx;
	overflow: hidden;
}
.tag-box{
	display: flex;
	row-gap:5rpx;
	column-gap:10rpx;
	flex-wrap: wrap; /* 允许换行 */
	
	.tag-item{
		display: inline-block;
		font-size: 24rpx;
		color:#1677FE;
		padding:10rpx;
		background-color:#EEF5FF;
		border-radius: 10rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		
	}
}
.list-item{
	image{
		width: 140rpx;
		height: 140rpx;
		margin-right:10rpx;
		flex-shrink: 0;
	}
	
	.right{
		flex:1;
		color:#000000
	}
}


</style>